﻿using System.Reflection;
using Command.CommunityToolkit.Attributes;
using log4net;
using MethodDecorator.Fody.Interfaces;

[module: Log]

namespace Command.CommunityToolkit.Attributes;

/// <summary>
/// 面向切面日志记录特性
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Assembly | AttributeTargets.Module)]
public class LogAttribute : Attribute, IMethodDecorator
{
    private ILog _log;
    private string? _msg;
    public LogAttribute(string? msg = null) { _msg = msg;
        _log = LogManager.GetLogger( "Info");
    }
    public void Init(object instance, MethodBase method, object[] args)
    {
        if (null == method) throw new ArgumentNullException("method");
        if (null == instance) throw new ArgumentNullException("instance");
        _log.Info($"{_msg} {string.Join(',',args)}");
    }

    public void OnEntry()
    {
        //_log.Info($"开始：{_msg}");
    }

    public void OnExit()
    {
        //_log.Info($"结束：{_msg}");
    }

    public void OnException(Exception exception)
    {
        _log.Info($"{_msg} 触发异常: {exception.GetType()}: {exception}");
    }
}